package com.codebo.homiematchbackend.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.codebo.homiematchbackend.annotation.AuthCheck;
import com.codebo.homiematchbackend.common.BaseResponse;
import com.codebo.homiematchbackend.common.ErrorCode;
import com.codebo.homiematchbackend.common.ResultUtils;
import com.codebo.homiematchbackend.config.CosClientConfig;
import com.codebo.homiematchbackend.constant.UserConstant;
import com.codebo.homiematchbackend.exception.BusinessException;
import com.codebo.homiematchbackend.exception.ThrowUtils;
import com.codebo.homiematchbackend.manager.CosManager;
import com.codebo.homiematchbackend.model.dto.file.FileUploadRequest;
import com.codebo.homiematchbackend.model.entity.User;
import com.codebo.homiematchbackend.service.UserService;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Slf4j
@RequestMapping("/file")
@RestController
public class FileController
{
    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private UserService userService;

    @PostMapping("/blog/upload")
    public BaseResponse<String> uploadBlogFile(@RequestPart("file") MultipartFile multipartFile,
                                               HttpServletRequest httpServletRequest)
    {
        //1.校验参数
//        User loginUser = userService.getLoginUser(httpServletRequest);
//        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCode.PARAMS_ERROR, "文件为空");
        //2.构建上传路径
        String filename = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        filename = String.format("%s-%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(filename));
        String filePath = String.format("/picture/blog/%s", filename);
        //3.上传文件
        File file = null;
        try
        {
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete)
            {
                log.error("文件上传失败, filepath = {}", filePath);
            }
            // 返回可访问的url
            return ResultUtils.success(cosClientConfig.getHost() + filePath);
        } catch (Exception e)
        {
            log.error("文件上传出现错误，filepath = {}", filePath);
        }
        return null;

    }

//    @PostMapping("/upload")
//    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
//                                           FileUploadRequest fileUploadRequest,
//                                           HttpServletRequest httpServletRequest)
//    {
//        //1.校验文件
//        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCode.PARAMS_ERROR);
//        ThrowUtils.throwIf(fileUploadRequest == null, ErrorCode.PARAMS_ERROR);
//        //判断是否重复上传
//        if (fileUploadRequest.getId()!=null)
//        {
//            //若为重复上传，则判断文件是否存在
//            //根据应用类型判断从哪个表查
//            switch (fileUploadRequest.getUseType())
//            {
//                case 0:
//                    //判断该文件是否已存在
//                    userService.getUserVO(fileUploadRequest.getId());
//                    //从team表中查
//                    break;
//                case 1:
//                    //判断该文件是否已存在
//                    //从blog表中查
//                    break;
//                case 2:
//                    //判断该文件是否已存在
//                    //从user表中查
//                    break;
//            }
//
//
//        }
//
//
//        //2.构建路径
//        String filename = multipartFile.getOriginalFilename();
//        //修改文件名为：time-uuid.xxx
//        String uuid = RandomUtil.randomString(16);
//        filename = String.format("%s-%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(filename));
//        //根据使用类型来构建不同路径
//        fileUploadRequest.
//
//
//        String filePath = String.format("/%s/%s", filename);
//        File file = null;
//        try
//        {
//            file = File.createTempFile(filePath, null);
//            multipartFile.transferTo(file);
//            cosManager.putObject(filePath, file);
//            // 删除临时文件
//            boolean delete = file.delete();
//            if (!delete)
//            {
//                log.error("file delete error, filepath = {}", filePath);
//            }
//            // 返回可访问的url
//            return ResultUtils.success(filePath);
//        } catch (Exception e)
//        {
//            log.error()
//        }
//
//
//        String filepath = String.format("/%s/%s", filename);
//    }


    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile)
    {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try
        {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问的地址
            return ResultUtils.success(filepath);
        } catch (Exception e)
        {
            log.error("文件上传失败, filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally
        {
            if (file != null)
            {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete)
                {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download/")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException
    {
        COSObjectInputStream cosObjectInput = null;
        try
        {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e)
        {
            log.error("file download error, filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally
        {
            // 释放流
            if (cosObjectInput != null)
            {
                cosObjectInput.close();
            }
        }

    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/delete")
    public BaseResponse<Boolean> testDeleteFile(String filepath)
    {
        try
        {
            cosManager.deleteObject(filepath);
            return ResultUtils.success(true);
        } catch (Exception e)
        {
            log.error("file delete error, filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
    }
}
